#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpi.h>
typedef struct{
	int loc;
	int num;
}Sort_rank;
int main(int argc, char *argv[])
{
	int rank, size, i, j;
	Sort_rank *old, *arr, *new;
	old = NULL;
	new = NULL;
	arr = NULL;
	MPI_Comm comm = MPI_COMM_WORLD;
	MPI_Init(&argc, &argv);
	MPI_Comm_size(comm, &size);
	MPI_Comm_rank(comm, &rank);
	if(rank == 0)
		arr = (Sort_rank *)malloc(sizeof(Sort_rank) * size);
	old = (Sort_rank*)malloc(sizeof(Sort_rank));
	new = (Sort_rank*)malloc(sizeof(Sort_rank));
	srand((unsigned) time(NULL)+rank*2);
	old->num = rand() % (size*3);
	old->loc = rank;
	MPI_Gather(old, 1, MPI_2INT, arr, 1, MPI_2INT, 0, comm);
	if(rank == 0)
	{
		for(i=0;i<size-1;i++)
			for(j=0;j<size-1-i;j++)
				if(arr[j].num>arr[j+1].num)
				{
					Sort_rank temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
	}
	MPI_Scatter(arr, 1, MPI_2INT, new, 1, MPI_2INT, 0, comm);
	printf("process %d, number %d, rank %d\n", rank, old->num, new->loc);
	MPI_Finalize();
	return 0;
}